<?php

class TKClient
{

    private $api_url = 'http://api.translatekarate.com/1.0/';
    private $project_id;
    private $api_secret;
    private $signature;

    public function __construct($project_id, $api_secret)
    {
        $this->api_secret = $api_secret;
        $this->project_id = $project_id;
    }

    private function signRequest($arguments)
    {
        ksort($arguments);

        foreach ($arguments as $key => $value)
        {
            $value = urlencode($value);
            $value = str_replace("%7E", "~", $value);
            $value = str_replace("+", "%20", $value);
            $data[] = urlencode($key) . '=' . $value;
        }

        $hash_base = implode('&', $data);
        $hash = hash_hmac('sha256', $hash_base, $this->api_secret, true);

        $this->signature = base64_encode($hash);

        return $this;
    }

    private function request($api_function, $arguments)
    {
        $arguments['project_id'] = $this->project_id;
        $this->signRequest($arguments);

        $arguments['sign'] = $this->signature;

        $resource = curl_init();

        curl_setopt($resource, CURLOPT_URL, $this->api_url . $api_function);
        curl_setopt($resource, CURLOPT_POST, 1);
        curl_setopt($resource, CURLOPT_POSTFIELDS, $arguments);
        curl_setopt($resource, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($resource, CURLOPT_TIMEOUT, 5);

        $response = curl_exec($resource);

        return $response;
    }

    public function pushPotFile($content)
    {
        $params = array(
            'pot-content' => $content
        );

	$response = $this->request('files.push-pot', $params);        
        return json_decode($response);
    }

    public function getMoFile($locale)
    {
        $params = array(
            'locale' => $locale
        );

        return $this->request('files.get-mo', $params);
    }
}